func sdiv*(a, b: SomeInteger): SomeInteger {.inline.} =
  ## Sane integer division, aka floor division.
  ## Always rounds down.
  ##
  ## For all integers, `a.sdiv(b) * b + a.smod(b) == a`.
  if b >= 0:
    if a >= 0:
      a div b
    else:
      (a + 1) div b - 1
  else:
    sdiv(-a, -b)

func smod*(a, b: SomeInteger): SomeInteger {.inline.} =
  ## Sane integer modulo.
  ## Always in range `0..<b` for positive b
  ## and `b+1..0` for negative b.
  ##
  ## For all integers, `a.sdiv(b) * b + a.smod(b) == a`.
  if b >= 0:
    if a >= 0:
      a mod b
    else:
      b + (a + 1) mod b - 1
  else:
    -smod(-a, -b)

proc updateMin*[T](x: var T, y: T): bool =
  ## If `y < x`, sets x to y.
  ## Returns whether this was the case.
  result = y < x
  if result:
    x = y

proc updateMax*[T](x: var T, y: T): bool =
  ## If `y > x`, sets x to y.
  ## Returns whether this was the case.
  result = y > x
  if result:
    x = y
